package timeslice
{
	import display.ImageSlot;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.geom.ColorTransform;
	
	import global.$R;
	import global.$talkScene;
	
	import slices.PlayTalkAvg;
	import slices.TimeSlice;
	import globals.$athena;
	
	import resources.RTProfile;
	import slices.InvokeFunction;
	import slices.TransformColor;
	
	public class TalkSceneTalk extends TimeSlice
	{
		public var from:Object;
		public var content:String;
		public var fromName:String;
		public var express:int;
		public var changingExpress:TimeSlice;
		
		public function TalkSceneTalk(from:Object, content:String, express:int=0, fromName:String=null)
		{
			super();
			this.from = from;
			this.content = content;
			this.fromName = fromName;
			this.express = express;
		}
		
		override public function onStart():void {
			if (fromName == null) {
				fromName = RTProfile.nameMap[from];
			}
			if ($talkScene.fontID != from) {
				var back:DisplayObject = $talkScene.findChar($talkScene.fontID);
				var font:DisplayObject = $talkScene.findChar(from);
				var toFront:TransformColor = new TransformColor(font, new ColorTransform(1,1,1), 200);
				var toBack:TransformColor = new TransformColor(back, new ColorTransform(0.4, 0.4, 0.4), 200);
				toFront.appendNext(new InvokeFunction(playText));
				$athena.addTimeSlice(toFront);
				$athena.addTimeSlice(toBack);
				$talkScene.fontID = from;
			} else {
				playText();
			}
			if ($talkScene.exps[from] != express) {
				var pf:DisplayObject = $R.getProfile(from, express);
				pf.x = -pf.width/2;
				changingExpress = ($talkScene.findChar(from) as ImageSlot).changeTo(pf, 0.05, 0.04);
				changingExpress.appendNext(new InvokeFunction(onChangeExpressOver));
				$talkScene.exps[from] = express;
			}
		}
		
		private function playText():void {
			$talkScene.textPanel.contentTF.text = "";
			$talkScene.textPanel.nameTF.text = fromName;
			var speak:PlayTalkAvg = new PlayTalkComma($talkScene.textPanel.contentTF);
			speak.addInput("text", content);
			speak.appendNext(new InvokeFunction(onSpeakOver));
			$athena.addTimeSlice(speak);			
		}
		
		private var _click:Boolean;
		
		private function onChangeExpressOver():void {
			changingExpress = null;
			if (_click) {
				isEnd = true;
			}
		}
		
		private function onSpeakOver():void {
			globalMouseClick = onMouseClick;			
		}
		
		private function onMouseClick(e:Event):void {
			if (changingExpress == null) {
				isEnd = true;	
			} else {
				_click = true;
			}
		}
	}
}